#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: shijianbo
@Email:
@Time: 2022/6/16 15:28
@File: Aml__init__.py.py
"""
from copy import deepcopy
from .oracle import OracleUtil
from .mysql import MysqlUtil
from .oceanbase import OceanBaseUtil
from .dameng import DaMengUtil
from .mssql import MssqlUtil
from .postgresql import PostgreSqlUtil
from .redisUtil import redisUtil
from ..env import Env

DB_CLASS = {
    'oracle': OracleUtil,
    'mysql': MysqlUtil,
    'tdsql': MysqlUtil,
    'oceanbase': OceanBaseUtil,
    'dm': DaMengUtil,
    'mssql': MssqlUtil,
    'postgresql': PostgreSqlUtil
}


def getDb(env=None, **kwargs):
    '''
    返回连接对象
    '''
    _env = Env(env)
    dbconfig =_env.dbConifg
    if kwargs:
        dbconfig.update(kwargs)
    _type = _env.dbType
    if _type in DB_CLASS:
        return DB_CLASS[_type](**dbconfig)
    else:
        raise Exception(f'{_type}暂不支持，目前支持mysql、oracle、oceanbase、dameng、mssql、postgresql，后续计划添加db2以及nosql相关数据库')


def execsql(sql, env=None, **kwargs):
    '''
    执行sql
    '''
    # key是否统一大写
    toup=kwargs.get('toup',True)
    # 是否转换为字符串
    tostr=kwargs.get('tostr',True)
    _env=Env(env)
    dbconfig=_env.dbConifg
    _type=_env.dbType
    result=[]
    if _type in DB_CLASS:
        with DB_CLASS[_type](**dbconfig) as db:
            result+=db.execsql(sql)
    else:
        raise Exception(f'{_type}暂不支持，目前支持mysql、oracle、oceanbase、dameng、mssql、postgresql，后续计划添加db2以及nosql相关数据库')
    # 类型转换&大小写切换
    for index,item in enumerate(deepcopy(result)):
        for k, v in item.items():
            if toup:
                result[index].pop(k)
                k=k.upper()
                result[index][k] = v
            if tostr:
                if not isinstance(v, str):
                    result[index][k] = str(v)
    return result